package com.epoint.mobileoa.ui.photo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.Toast;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.tools.DateHelp;
import com.epoint.mobileoa.tools.GetBitmap;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.SDCard;
import com.epoint.mobileoa.tools.ToastHelp;

/**
 * 拍照界面
 * 
 * @author lilin
 * @date 2011-9-3 下午12:22:10
 * @ClassName: Main
 * @Description: TODO
 */
public class TakePhotoView extends Activity implements
		SurfaceHolder.Callback, OnClickListener, PictureCallback {
	private Camera camera;// 相机
	private boolean isboolean = true;
	public static final int ITEM0 = Menu.FIRST;
	public static final int ITEM1 = Menu.FIRST + 1;
	public static final int ITEM2 = Menu.FIRST + 2;
	private SurfaceView surfaceView;

	private ImageView preView_iv;// 预览
	// public static int photosavepath = 0;
	// public static int moduleName = 0;

	private Button take_btn;// 拍照
	private Button tool_btn;// 工具
	private Button takeself_btn;// 自拍

	private CheckBox istakeself_cb;// 是否开启自拍

	private Chronometer chronometer;// 计时器
	private int taketime = 3;// 自动拍摄时间

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.qwt_takephotoview);
		initView();
	}

	public void initView() {
		surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
		take_btn = (Button) findViewById(R.id.takepic_btn);
		tool_btn = (Button) findViewById(R.id.tool_btn);
		takeself_btn = (Button) findViewById(R.id.takeself_btn);

		take_btn.setOnClickListener(this);
		tool_btn.setOnClickListener(this);
		takeself_btn.setOnClickListener(this);

		istakeself_cb = (CheckBox) findViewById(R.id.istakeself_cb);

		chronometer = (Chronometer) findViewById(R.id.chronometer);

		chronometer
				.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
					public void onChronometerTick(Chronometer chronometer) {
						if (SystemClock.elapsedRealtime()
								- chronometer.getBase() >= taketime * 1000) { // 如果开始计时到现在超过了startime秒
							chronometer.stop();
							chronometer.setBase(SystemClock.elapsedRealtime());
							camera.takePicture(null, null,
									TakePhotoView.this);

						}
					}
				});

		// 设置surfaceView
		int rx = Integer.valueOf(getResources().getString(R.string.ratio_x));
		int ry = Integer.valueOf(getResources().getString(R.string.ratio_y));
		surfaceView.getHolder().setFixedSize(rx, ry); // 设置分辨率
		surfaceView.getHolder()
				.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceView.getHolder().addCallback(this);// 回调

		preView_iv = (ImageView) findViewById(R.id.myImageView);

		// 设置默认图片
		Bitmap bitmap = GetBitmap.getBitmap(TakePhotoView.this,
				R.drawable.preview2);
		// Bitmap newbitmap = GetBitmap.getZoomRotateBitmap(bitmap, 240, 320,
		// 0);
		preView_iv.setImageBitmap(bitmap);

		// 判断是否可以获得requestedOrientation属性
		if (TakePhotoView.this.getRequestedOrientation() == -1) {
			Toast.makeText(TakePhotoView.this, "系统的屏幕方无法获取!!", 3000)
					.show();
		} else {
			if (TakePhotoView.this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				// Main.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			} else if (TakePhotoView.this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
				TakePhotoView.this
						.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
		}

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.takepic_btn:// 拍照
			if (istakeself_cb.isChecked()) {
				take_btn.setBackgroundResource(R.drawable.take_picture2);
				takeself_btn.setEnabled(false);
				tool_btn.setEnabled(false);
				take_btn.setEnabled(false);
				chronometer.setBase(SystemClock.elapsedRealtime());// 设置开始讲时时间
				chronometer.start();// 开始计时

			} else {
				take_btn.setBackgroundResource(R.drawable.take_picture2);
				takeself_btn.setEnabled(false);
				tool_btn.setEnabled(false);
				take_btn.setEnabled(false);

				camera.takePicture(null, null, this);
			}

			break;
		case R.id.tool_btn:// 相册
			albumList();
			take_btn.setEnabled(false);
			takeself_btn.setEnabled(false);
			break;
		case R.id.takeself_btn:// 自拍
			takeself_btn.setBackgroundResource(R.drawable.take_picture2);
			takeself_btn.setEnabled(false);
			take_btn.setEnabled(false);
			tool_btn.setEnabled(false);
			chronometer.setBase(SystemClock.elapsedRealtime());// 设置开始讲时时间
			chronometer.start();// 开始计时
			break;
		default:
			break;
		}
	}

	/**
	 * @author lilin
	 * @date 2012-3-28 上午10:43:30
	 * @annotation
	 */
	private void albumList() {
		Intent intent = new Intent(TakePhotoView.this,
				PhotoListView.class);
		startActivity(intent);
		finish();
	}

	// 在界面尺寸改变时被调用，设置相机的参数（大小，格式）
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		if (isboolean) {
			camera.stopPreview();
		}
		// 相机参数设置
		Camera.Parameters para = camera.getParameters();
		// 图片格式
		para.setPictureFormat(PixelFormat.JPEG);
		// 开启闪光灯
		para.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
		// para.setPreviewSize(w, h);
		// 照片大小
		int pw = Integer.valueOf(getResources().getString(R.string.picwidth));
		int py = Integer.valueOf(getResources().getString(R.string.picheight));
		para.setPictureSize(pw, py);
		// para.set("rotation", 90);
		try {
			camera.setParameters(para);
		} catch (Exception e) {
			Log.e("camera.setParameters(para)", e.getMessage());
		}
		// 自动对焦
		// camera.autoFocus(null);
		try {
			camera.setPreviewDisplay(holder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		camera.startPreview();
		isboolean = true;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// 界面创建时被调用，一般是用来，打开相机，设置预览
		camera = Camera.open();// 不能放在构造函数里，否则产生不了预览效果
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		isboolean = false;
		camera.release();
	}

	// 捕捉相机拍到的图片
	public void onPictureTaken(byte[] _data, Camera camera) {
		// 使用ImageView预览图片
		try {
			Bitmap bitmap = BitmapFactory.decodeByteArray(_data, 0,
					_data.length);
			String formateDate1 = DateHelp.getFormateDate(1);
			// 现将图片进行缩放处理，再预览，原始是640*480，缩放后是120*90
			Bitmap preBitmap = GetBitmap
					.getZoomRotateBitmap(bitmap, 120, 90, 0);
			preView_iv.setImageBitmap(preBitmap);
			savepicture(bitmap, formateDate1);// 保存图片
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 保存图片
	public void savepicture(Bitmap bitmap, String formateDate) {
		// 格式一：2011-11-1 12-12-66 作为文件名
		String formateDate1 = formateDate;
		try {

			String photoName = formateDate1 + ".jpg";// 照片名称
			String photoPath = getResources().getString(
					R.string.photoPath_default);
			if (!SDCard.getFileSavePath(photoPath).toString().equals(null)) {
				File file = new File(SDCard.getFileSavePath(photoPath),
						photoName);// 创建图片文件
				FileOutputStream outStream = new FileOutputStream(file);
				bitmap.compress(CompressFormat.JPEG, 50, outStream);
				outStream.close();
				String text = "保存成功!";
				// 设置拍照按钮可用
				take_btn.setEnabled(true);
				takeself_btn.setEnabled(true);
				tool_btn.setEnabled(true);
				take_btn.setBackgroundResource(R.drawable.take_picture1);
				takeself_btn.setBackgroundResource(R.drawable.take_picture1);
				ToastHelp.showToast(getApplicationContext(), text);
			} else {
				ToastHelp.showToast(getApplicationContext(), "请插入内存卡！");
			}
			camera.stopPreview();
			camera.startPreview();// 开始预览

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			albumList();
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	// Menu菜单
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, ITEM0, 0, "相册");
		return true;
	}

	// Menu菜单点击事件
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ITEM0:// 相册
			albumList();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}